/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cat.ereza.customactivityoncrash.demo.slice;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;

import java.util.concurrent.Executors;

import cat.ereza.customactivityoncrash.LogUtil;
import cat.ereza.customactivityoncrash.ResourceTable;
import cat.ereza.customactivityoncrash.annotations.SuppressLint;
import cat.ereza.customactivityoncrash.config.CaocConfig;

/**
 * MainAbilitySlice extends AbilitySlice implements Component.ClickedListener
 */
public class MainAbilitySlice extends AbilitySlice implements Component.ClickedListener {
    private static final String TAG = "MainAbilitySlice";

    private ComponentContainer mView;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        mView = (ComponentContainer) LayoutScatter.getInstance(this).parse(ResourceTable.Layout_ability_main, null, false);
        setUIContent(mView);

        initView();

        // Test case 1
        customCrashAbilityTestCase();

        // Test case 2
        // defaultCrashAbilityTestCase();
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    private void initView() {
        Button crashMainThreadButton = (Button) mView.findComponentById(ResourceTable.Id_button_crash_main_thread);
        crashMainThreadButton.setClickedListener(this);

        Button crashBgThreadButton = (Button) mView.findComponentById(ResourceTable.Id_button_crash_bg_thread);
        crashBgThreadButton.setClickedListener(this);

        Button crashWithDelayButton = (Button) mView.findComponentById(ResourceTable.Id_button_crash_with_delay);
        crashWithDelayButton.setClickedListener(this);
    }

    // Set app bundle name to launch default error ability when crash occurs.
    private void defaultCrashAbilityTestCase() {
        CaocConfig.Builder.create()
                .bundleName("cat.ereza.customactivityoncrash.demo")
                .apply();
    }

    // Set app bundle name and error ability to launch custom error ability when crash occurs.
    private void customCrashAbilityTestCase() {
        CaocConfig.Builder.create()
                .bundleName("cat.ereza.customactivityoncrash.demo")
                .errorAbility("cat.ereza.customactivityoncrash.demo.CustomErrorAbility")
                .apply();
    }

    @SuppressLint("StaticFieldLeak") // For demo purposes we don't care about leaks
    @Override
    public void onClick(Component component) {
        switch (component.getId()){
            case ResourceTable.Id_button_crash_main_thread:
                LogUtil.info(TAG, "Crash main thread");
                throw new RuntimeException("I'm a cool exception and I crashed the main thread!");
            case ResourceTable.Id_button_crash_bg_thread:
                Executors.newSingleThreadExecutor().execute(new Runnable() {
                    @Override
                    public void run() {
                        LogUtil.info(TAG, "Crash background thread");
                        throw new RuntimeException("I'm also cool, and I crashed the background thread!");
                    }
                });
                break;
            case ResourceTable.Id_button_crash_with_delay:
                Executors.newSingleThreadExecutor().execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(5000);
                        } catch (InterruptedException e) {
                            LogUtil.error(TAG, "InterruptedException - "+e);
                        }
                        LogUtil.info(TAG, "Crash with delay(5s)");
                        throw new RuntimeException("I am a not so cool exception, and I am delayed, so you can check if the app crashes when in background!");
                    }
                });
                break;
        }
    }
}
